package com.cunjiankang.ui;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import com.cunjiankang.R;
import com.cunjiankang.adapter.GoodsGVAdapter;
import com.cunjiankang.bean.request.IntegralGoodsRequest;
import com.cunjiankang.bean.response.BaseResponse;
import com.cunjiankang.bean.response.IntegralGoodResponse;
import com.cunjiankang.bean.vo.Goods;
import com.cunjiankang.util.Contants;
import com.cunjiankang.util.HttpUtil;
import com.cunjiankang.util.PreferenceUtil;
import com.cunjiankang.util.TextViewUtil;
import com.cunjiankang.view.CustomProgressDialog;
import com.google.gson.Gson;
import jp.ksksue.driver.serial.FTDriver;
import jp.ksksue.driver.serial.HexUtils;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;

import java.util.List;

/**
 * 
 * @ClassName: IntegralDHActivity
 * @Description:
 * @author liyongqiang
 * @date 2015-3-5 下午11:39:54
 * 
 */
public class IntegralDHActivity extends BaseActivity {

	private List<Goods> list;
	private GoodsGVAdapter adapter;
	@BindView(id = R.id.gv_goods)
	private GridView gvGoods;
	@BindView(id = R.id.no_data)
	private TextView noData;
	@BindView(id = R.id.tv_info)
	private TextView tvInfo;
	@BindView(id = R.id.btn_back, click = true)
	private Button btnBack;
	private FTDriver mSerial;
	final int SERIAL_BAUDRATE = FTDriver.BAUD115200;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_integral_dh);
		super.setRootView();
	}

	@Override
	public void initData() {
		super.initData();

		String username = PreferenceUtil.readString(this, Contants.SP.username);
		String integral = PreferenceUtil.readString(IntegralDHActivity.this, Contants.SP.integral);
		integral = integral == null ? "0" : integral;
		tvInfo.setText(String.format(getString(R.string.user_info), username,
				integral));
		TextViewUtil textViewUtil = new TextViewUtil();
		String info = String.format(getString(R.string.user_info), username,
				integral);
		int start1 = info.indexOf(username);
		int end1 = start1 + username.length();
		int start2 = info.indexOf(integral);
		int end2 = start2 + integral.length();
		tvInfo.setText(textViewUtil.getForegroundColorSpan(this, info, start1,
				end1, start2, end2, "#e95013"));
		queryGoods();
	}

	@Override
	public void initWidget() {
		super.initWidget();
		gvGoods.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Contants.starTime = System.currentTimeMillis();
				return false;
			}
		});
		mSerial = new FTDriver(
				(UsbManager) getSystemService(Context.USB_SERVICE), this);

		PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0,
				new Intent("jp.ksksue.sample.USB_PERMISSION"), 0);
		mSerial.setPermissionIntent(permissionIntent);
		// Broadcast listen for new devices
		IntentFilter filter = new IntentFilter();
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		registerReceiver(mUsbReceiver, filter);
		if (mSerial.begin(SERIAL_BAUDRATE)) {
			//Toast.makeText(this, "true", Toast.LENGTH_SHORT).show(); 
		}else{
			//Toast.makeText(this, "false", Toast.LENGTH_SHORT).show(); 
		}
	}
	private int Rotate = 0;// 旋转角度
	public static String info = "\n\ttitle\n" +
			"--------------------------------\n" +
			"尊敬的username会员：\n" +
			"您目前的积分为integral。\n" +
			"--------------------------------\n" +
			"您选择的兑换商品为\n\t " +
			"name\n\t " +
			"number积分兑换\n\n " +
			"-------------------------------\n" +
			"\t\t    " +
			"time";

	public void print(int poiston) {
		String title = PreferenceUtil.readString(this, Contants.SP.groupName) == null ? " " : PreferenceUtil.readString(this, Contants.SP.groupName);
		String username = PreferenceUtil.readString(this, Contants.SP.username) == null ? " " : PreferenceUtil.readString(this, Contants.SP.username);
		String integral = PreferenceUtil.readString(this, Contants.SP.integral) == null ? " " : PreferenceUtil.readString(this, Contants.SP.integral);
		String name = list.get(poiston).name == null ? " " : list.get(poiston).name;

		String etstring = info
				.replace("username", username)
				.replace("integral", integral)
				.replace("name", name)
				.replace("number", "100")
				.replace("title", title)
				.replace("time", "20" + SystemTool.getDataTime("yy-MM-dd"))
				.replace("会员查询系统","积分兑换卷");


		//Toast.makeText(this, etstring, Toast.LENGTH_SHORT).show();
		KJLoger.debug("printstr:" + etstring);
		if (etstring != null && !"".equals(etstring)) {
			String strWrite = HexUtils.getHexResult(etstring);
			byte[] etBytes = HexUtils.hexStr2Bytes(strWrite);
			byte[] etBytes2 = HexUtils.hexStr2FeedLine(6);
			byte[] etBytes3 = HexUtils.hexStr2CutPaper(0);
			try {
				mSerial.write(HexUtils.SetPrintRotate(Rotate));
				mSerial.write(HexUtils.SetUlineModel(0));
				mSerial.write(HexUtils.SetPrintModel(1, 1));
//				mSerial.write(etBytes2);
				mSerial.write(etBytes, etBytes.length);
				mSerial.write(etBytes2);
				mSerial.write(etBytes3);
			} catch (Exception e) {
				e.printStackTrace();
				if (!mSerial.isConnected()) {
					IntentFilter filter = new IntentFilter();
					filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
					filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
					registerReceiver(mUsbReceiver, filter);
				}
			}
		}
	}

	private void queryGoods() {
		final IntegralGoodsRequest goodsRequest = new IntegralGoodsRequest();
		goodsRequest.type = Contants.ApiKey.jfdhsp;
		goodsRequest.grubid = PreferenceUtil.readString(this,
				Contants.SP.local_grubid, "");
		final Dialog dialog = CustomProgressDialog.createDialog(this)
				.setMessage(R.string.loading);
		dialog.show();
		HttpUtil.post(goodsRequest, new HttpCallBack() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				KJLoger.debug(goodsRequest.type + ":" + t);
				if (Contants.debug) {
					t = "{\"type\":\"jfdhsp\",\"flag\":\"success\",\"array\":[{\"id\":12,\"name\":\"���\",\"content\":\"500��ֶһ�\",\"img\":\"http://img11.360buyimg.com/n7/jfs/t631/350/768996630/494672/d156f343/548942ccN41fc6af9.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"},{\"id\":10,\"name\":\"�ؼ���ե�����\",\"content\":\"1000��ֶһ�\",\"img\":\"http://img10.360buyimg.com/n1/jfs/t691/258/1247685972/165467/bfc4650d/54c1a146N3da433fd.jpg\"}]}";
				}
				try{
				IntegralGoodResponse response = new Gson().fromJson(t,
						IntegralGoodResponse.class);
				if (BaseResponse.flag_success.equals(response.flag)) {
					if (null != response.array && response.array.size() > 0) {
						list = response.array;
						adapter = new GoodsGVAdapter(IntegralDHActivity.this,
								list);
						gvGoods.setAdapter(adapter);
						gvGoods.setVisibility(View.VISIBLE);
					} else {
						noData.setVisibility(View.VISIBLE);
					}
				} else {
					ViewInject.toast(getString(R.string.get_goods_error));
					noData.setVisibility(View.VISIBLE);
				}}catch (Exception e) {
//					Toast.makeText(IntegralDHActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
//					skipActivity(IntegralDHActivity.this, MainActivity.class);

					String username = PreferenceUtil.readString(IntegralDHActivity.this, Contants.SP.username);
					String integral = PreferenceUtil.readString(IntegralDHActivity.this, Contants.SP.integral);
					tvInfo.setText(String.format(getString(R.string.user_info), username,
							integral));
					TextViewUtil textViewUtil = new TextViewUtil();
					String info = String.format(getString(R.string.user_info), username,
							integral);
					int start1 = info.indexOf(username);
					int end1 = start1 + username.length();
					int start2 = info.indexOf(integral);
					int end2 = start2 + integral.length();
					tvInfo.setText(textViewUtil.getForegroundColorSpan(IntegralDHActivity.this, info, start1,
							end1, start2, end2, "#e95013"));

					System.out.println(e.toString());
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				KJLoger.debug(t.toString());
				noData.setVisibility(View.VISIBLE);
				if (SystemTool.checkNet(IntegralDHActivity.this)) {
					ViewInject.toast(getString(R.string.get_data_error));
				} else {
					ViewInject.toast(getString(R.string.net_error));
				}
			}

			@Override
			public void onFinish() {
				super.onFinish();
				dialog.dismiss();
			}
		},IntegralDHActivity.this);
	}

	@Override
	public void widgetClick(View view) {
		super.widgetClick(view);
		Contants.starTime = System.currentTimeMillis();
		switch (view.getId()) {
		case R.id.btn_back:
			finish();
			break;
		default:
			break;
		}
	}

	BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
				mSerial.usbAttached(intent);
				mSerial.begin(SERIAL_BAUDRATE);
			} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
				mSerial.usbDetached(intent);
			}
		}
	};

	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mUsbReceiver);
	};

}
